import { throttle } from "lodash-es";

const DRAWING_ID = "idGlobal";
const TREE_NODE_ID = "treeNodeId";
const FORM_CONF = "formConf";
const FORM_DATA = "formData";
const FORM_SAVE_DATA = "formSaveData";
const TEMP_FROM_DATA = "tempFormData";
const LAST_FORM_DATA_ID = "lastFormDataId";

export function getTreeNodeId() {
  const str = localStorage.getItem(TREE_NODE_ID);
  if (str) return parseInt(str, 10);
  return 100;
}

export function saveTreeNodeId(id: string) {
  localStorage.setItem(TREE_NODE_ID, `${id}`);
}

/**
 * 缓存没提交的数据
 * @param key
 */
export function getFormData(key: string) {
  const str = localStorage.getItem(`${FORM_DATA}:${key}`);
  if (str) return JSON.parse(str);
  return null;
}

export const saveFormData = throttle(function (obj: any, key: string) {
  if (key) localStorage.setItem(`${FORM_DATA}:${key}`, JSON.stringify(obj));
}, 800);

export function removeFormData(key: string) {
  if (key) localStorage.removeItem(`${FORM_DATA}:${key}`);
}

// 上次提交的数据
export function getFormSaveData(key: string) {
  const str = localStorage.getItem(`${FORM_SAVE_DATA}:${key}`);
  if (str) return JSON.parse(str);
  return null;
}

export function saveFormSaveData(obj: any, key: string) {
  if (key) localStorage.setItem(`${FORM_SAVE_DATA}:${key}`, JSON.stringify(obj));
}

// 缓存临时数据 人脸识别跳转时使用
export function saveTempFormData(obj: any, key: string) {
  if (key) localStorage.setItem(`${TEMP_FROM_DATA}:${key}`, JSON.stringify(obj));
}

export function getTempFormData(key: string) {
  const str = localStorage.getItem(`${TEMP_FROM_DATA}:${key}`);
  if (str) return JSON.parse(str);
  return null;
}

export function removeTempFormData(key: string) {
  if (key) localStorage.removeItem(`${TEMP_FROM_DATA}:${key}`);
}

/**
 * 保存最后一次提交的表单的数据
 */
export function saveLastFormSubmitRes(resData: any, key: string) {
  if (key) localStorage.setItem(`${LAST_FORM_DATA_ID}:${key}`, JSON.stringify(resData));
}

/**
 * 获取最后一次的
 */
export function getLastFormSubmitRes(key: string) {
  return localStorage.getItem(`${LAST_FORM_DATA_ID}:${key}`);
}
